package com.uuah.server.transport;

import com.uuah.server.api.endpoint.IUuahEndpoint;
import com.uuah.server.api.transport.IMessageDispatcher;
import com.uuah.server.api.transport.IMessageDispatcherFactory;
import com.uuah.server.exception.AbstractUuahServerException;
import com.uuah.utils.ClassUtils;

/**
 *
 * TODO comment ...
 *
 * <p>
 * update record:updator，update time，update content and version
 * </p>
 *
 * @author <a href="jonny_quan@hotmail.com">jonny</a>
 * @date 2009 2009-3-27 下午03:11:03
 * @version 1.0.0
 */
public abstract class AbstractMessageDispatcherFactory implements
		IMessageDispatcherFactory {

	public AbstractMessageDispatcherFactory() {
		super();
	}

	/**
	 * This default implementation of
	 * {@link IMessageDispatcherFactory#isCreateDispatcherPerRequest()} returns
	 * <code>false</code>, which means that dispatchers are pooled according to
	 * their lifecycle as described in {@link IMessageDispatcher}.
	 *
	 * @return <code>false</code> by default, unless overwritten by a subclass.
	 */
	public boolean isCreateDispatcherPerRequest() {
		return false;
	}

	public abstract IMessageDispatcher create(IUuahEndpoint endpoint)
			throws AbstractUuahServerException;

	public void activate(IUuahEndpoint endpoint, IMessageDispatcher dispatcher)
			throws AbstractUuahServerException {
		dispatcher.activate();
	}

	public void destroy(IUuahEndpoint endpoint, IMessageDispatcher dispatcher) {
		dispatcher.dispose();
	}

	public void passivate(IUuahEndpoint endpoint, IMessageDispatcher dispatcher) {
		dispatcher.passivate();
	}

	public boolean validate(IUuahEndpoint endpoint, IMessageDispatcher dispatcher) {
		// Unless dispatchers are to be disposed of after every request, we
		// check if
		// the dispatcher is still valid or has e.g. disposed itself after an
		// exception.
		return (this.isCreateDispatcherPerRequest() ? false : dispatcher
				.validate());
	}

	// @Override
	public String toString() {
		final StringBuffer sb = new StringBuffer(60);
		sb.append(ClassUtils.getSimpleName(this.getClass()));
		sb.append("{this=").append(
				Integer.toHexString(System.identityHashCode(this)));
		sb.append(", createDispatcherPerRequest=").append(
				this.isCreateDispatcherPerRequest());
		sb.append('}');
		return sb.toString();
	}

}
